package com.legendshop.code.freemarker;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.legendshop.code.config.Config;
import com.legendshop.code.freemarker.model.LowerFirstCharacter;
import com.legendshop.code.freemarker.model.UpperFirstCharacter;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public abstract class AbstractBulidTemplet implements BulidTemplet {

	private final static Logger logger = LoggerFactory.getLogger(AbstractBulidTemplet.class);

	private static Configuration freemarkerCfg;
	
	public AbstractBulidTemplet(){
		logger.info("start init " + this.getClass());
		freemarkerCfg = new Configuration();
		String path = null;
		try {
			path = java.net.URLDecoder.decode(AbstractBulidTemplet.class.getResource("").getPath(),"utf-8");  
			freemarkerCfg.setDirectoryForTemplateLoading(new File(path + "template"));
		} catch (Exception e) {
			logger.error("freemarkerCfg.setDirectoryForTemplateLoading error, path = " + path, e);
		}
		freemarkerCfg.setObjectWrapper(new DefaultObjectWrapper());
		freemarkerCfg.setDefaultEncoding("UTF-8");
		freemarkerCfg.setSharedVariable("upperFirstChar", new UpperFirstCharacter());// 设置公用变量
		freemarkerCfg.setSharedVariable("lowerFirstChar", new LowerFirstCharacter());// 设置公用变量
	}
	/**
	 * 设置freemarker参数
	 * 
	 * @param dir
	 * @throws IOException
	 */


	protected boolean buildJavaFile(String templateFileName, Map<?, ?> paramMap, String outputDir, String fileName, boolean overWritten) {
		String usrDir = getBaseDir();
		outputDir = usrDir + outputDir;
		File javaFile = null;
		Writer out = null;
		try {
			Template template = freemarkerCfg.getTemplate(templateFileName);
			template.setEncoding("UTF-8");
			// 创建生成文件目录
			File file = new File(outputDir);
			if (!file.exists()) {
				file.mkdirs();
			}
			if (!outputDir.endsWith("/")) {
				outputDir = outputDir + "/";
			}
			javaFile = new File(outputDir + fileName);
			logger.info("Create file is " + javaFile);
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(javaFile,overWritten), "UTF-8"));
			template.process(paramMap, out);
			out.flush();
			return true;
		} catch (TemplateException ex) {
			logger.error("Build Error : " + templateFileName, ex);
			return false;
		} catch (IOException e) {
			logger.error("Build Error : " + templateFileName, e);
			e.printStackTrace();
			return false;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	protected Map<String, Object> getParamMap(String tableName) {
		Map<String, Object> paramMap = new HashMap<String, Object>();

		Config.getInstance().getContextMap(tableName);
		return paramMap;
	}

	protected static String getBaseDir() {
		String usrDir = System.getProperty("user.dir");
		if (usrDir.endsWith("/lib")) {
			usrDir = usrDir.substring(0, usrDir.length() - 5);
		}
		return usrDir;
	}
}
